<script setup lang="tsx">
import { onMounted, ref } from 'vue';
import { Popconfirm } from 'ant-design-vue';
import { $t } from '@/locales';
import AuthButton from '@/components/common/auth-button.vue';
import { batchDeleteDictItems, deleteDictItem, fetchAllDictTypes, fetchDictItemList } from '@/service/api/dict';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import TableHeaderOperation from '@/components/advanced/table-header-operation.vue';
import DictOperateModal from './modules/dict-operate-modal.vue';
import DictViewDrawer from './modules/dict-view-drawer.vue';
import DictSearch from './modules/dict-search.vue';

// 引入useTableOperate钩子

interface DictItem {
  id: number;
  dictType: string;
  itemCode: string;
  itemName: string;
  description?: string;
  createBy: string;
  createTime: string;
  updateBy: string;
  updateTime: string;
}

interface DictSearchParams {
  current?: number;
  size?: number;
  dictType?: string;
  itemCode?: string;
  itemName?: string;
}

const { tableWrapperRef, scrollConfig } = useTableScroll();

// 搜索参数
const searchParams = ref<DictSearchParams>({
  current: 1,
  size: 10,
  dictType: undefined,
  itemCode: undefined,
  itemName: undefined
});

// 字典类型列表
const dictTypes = ref<string[]>([]);

// 初始化字典类型数据
onMounted(async () => {
  try {
    const res = await fetchAllDictTypes();
    dictTypes.value = res.data || [];
  } catch (error) {
    window.$message?.error(`获取字典类型失败：${(error as any).message}`);
  }
});

// 使用服务层API函数

const {
  columns,
  columnChecks,
  data,
  loading,
  mobilePagination,
  getData,
  getDataByPage,
  resetSearchParams,
  updateSearchParams
} = useTable({
  apiFn: fetchDictItemList,
  apiParams: {
    current: 1,
    size: 10,
    dictType: undefined,
    itemCode: undefined,
    itemName: undefined
  },
  columns: () => [
    {
      key: 'id',
      title: 'ID',
      align: 'center',
      dataIndex: 'id',
      width: '5%'
    },
    {
      key: 'dictType',
      title: '字典类型',
      align: 'center',
      dataIndex: 'dictType',
      width: '15%'
    },
    {
      key: 'itemCode',
      title: '字典编码',
      align: 'center',
      dataIndex: 'itemCode',
      width: '15%'
    },
    {
      key: 'itemName',
      title: '映射名称',
      align: 'center',
      dataIndex: 'itemName',
      width: '15%'
    },
    {
      key: 'description',
      title: '描述',
      align: 'center',
      dataIndex: 'description',
      customRender: ({ record }) => {
        return record.description || '-';
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center' as const,
      width: 180,
      customRender: ({ record }: { record: any }) => (
        <div class="flex-center gap-8px">
          <AuthButton permission="DICT_VIEW" onClick={() => handleView(record)} type="primary" ghost size="small">
            {$t('common.view')}
          </AuthButton>
          <AuthButton permission="DICT_EDIT" onClick={() => edit(record.id)} type="primary" ghost size="small">
            {$t('common.edit')}
          </AuthButton>
          <Popconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id)}>
            <AuthButton permission="DICT_DELETE" danger size="small">
              {$t('common.delete')}
            </AuthButton>
          </Popconfirm>
        </div>
      )
    }
  ]
});

// 查看功能状态
const viewDrawerVisible = ref(false);
const viewingData = ref<DictItem | null>(null);

// 使用useTableOperate管理表格操作
const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  rowSelection,
  onBatchDeleted,
  onDeleted
} = useTableOperate(data as any, getData);

// 查看字典项详情
function handleView(record: DictItem) {
  viewingData.value = record;
  viewDrawerVisible.value = true;
}

// 批量删除操作
async function handleBatchDelete() {
  if (checkedRowKeys.value.length === 0) {
    window.$message?.warning('请选择要删除的字典项');
    return;
  }

  try {
    await batchDeleteDictItems(checkedRowKeys.value.map(id => Number(id)));
    onBatchDeleted();
  } catch (error) {
    window.$message?.error(`批量删除失败：${(error as any).message}`);
  }
}

// 单个删除操作
async function handleDelete(id: number) {
  try {
    await deleteDictItem(id);
    onDeleted();
  } catch (error) {
    window.$message?.error(`删除失败：${(error as any).message}`);
  }
}

// 搜索
function handleSearch() {
  // 更新搜索参数并获取数据
  updateSearchParams(searchParams.value);
  getData();
}

function edit(id: string) {
  handleEdit(Number(id));
}
// 重置搜索
function handleReset() {
  // 重置搜索参数对象，清空搜索栏内容
  searchParams.value = {
    current: 1,
    size: 10,
    dictType: undefined,
    itemCode: undefined,
    itemName: undefined
  };
  resetSearchParams();
  getData();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-10px overflow-hidden lt-sm:overflow-auto">
    <!-- 搜索区域 -->
    <DictSearch v-model:model="searchParams" :dict-types="dictTypes" @search="handleSearch" @reset="handleReset" />

    <!-- 表格区域 -->
    <ACard
      title="字典管理"
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #extra>
        <div class="flex-center gap-8px">
          <TableHeaderOperation
            v-model:columns="columnChecks"
            :disabled-delete="checkedRowKeys.length === 0"
            :loading="loading"
            add-permission="DICT_ADD"
            delete-permission="DICT_DELETE"
            @add="handleAdd"
            @delete="handleBatchDelete"
            @refresh="getData"
          />
        </div>
      </template>
      <ATable
        ref="tableWrapperRef"
        :columns="columns"
        :data-source="data"
        :row-selection="rowSelection"
        size="small"
        :loading="loading"
        row-key="id"
        :scroll="scrollConfig"
        :pagination="{
          ...mobilePagination,
          total: Number(mobilePagination.total),
          pageSize: Number(mobilePagination.pageSize)
        }"
        class="h-full"
      />
      <DictOperateModal
        v-model:open="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :dict-types="dictTypes"
        @submitted="getDataByPage"
      />

      <!-- 查看字典项详情抽屉 -->
      <DictViewDrawer v-model:model-value="viewDrawerVisible" title="查看字典项详情" :width="600">
        <div v-if="viewingData" class="dict-view-content">
          <ARow :gutter="16">
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">字典类型：</label>
                <span class="info-value">{{ viewingData.dictType }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">字典编码：</label>
                <span class="info-value">{{ viewingData.itemCode }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">字典名称：</label>
                <span class="info-value">{{ viewingData.itemName }}</span>
              </div>
            </ACol>

            <ACol :span="24">
              <div class="info-item">
                <label class="info-label">描述：</label>
                <span class="info-value">{{ viewingData.description || '-' }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">创建时间：</label>
                <span class="info-value">{{ viewingData.createTime || '-' }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">更新时间：</label>
                <span class="info-value">{{ viewingData.updateTime || '-' }}</span>
              </div>
            </ACol>
          </ARow>
        </div>
      </DictViewDrawer>
    </ACard>
  </div>
</template>

<style scoped>
.dict-view-content {
  padding: 16px 0;
}

.info-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 8px;
}

.info-value {
  color: #333;
  flex: 1;
}

.dark .info-label {
  color: #aaa;
}

.dark .info-value {
  color: #eee;
}
</style>
